package docs

import (
	"errors"
	"io/ioutil"
	"os"
	"regexp"
	"strings"
)

type SubscriptionArticleGenerator struct {
	MuXiCodeDocsPath        string
	SubscriptionArticleDir  string
	WebDomain               string
}

func (s *SubscriptionArticleGenerator) Generate() error {
	if err := s.Validate(); err != nil {
		return err
	}
	// 格式化md文件中图片的位置由绝对路径变为相对路径
	filename := s.GetLastFileAllName(s.MuXiCodeDocsPath)
	targetPath := s.SubscriptionArticleDir + filename
	bs, err := os.ReadFile(s.MuXiCodeDocsPath)
	if err != nil {
		return nil
	}
	// write to file
	articleContent := s.replaceURLs(string(bs), s.WebDomain)
	return ioutil.WriteFile(targetPath, []byte(articleContent), 0644)
}

func (s *SubscriptionArticleGenerator) replaceURLs(article string, domain string) string {
	// 定义正则表达式
	re := regexp.MustCompile(`!\[(.*?)\]\((.*?\.png)\)`)
	// 替换字符串
	replacedArticle := re.ReplaceAllString(article, "![${1}]("+domain+"${2})")
	return replacedArticle
}

func (s *SubscriptionArticleGenerator) GetLastFileAllName(path string) string {
	files := strings.Split(path, "\\")
	return files[len(files)-1]
}

func (s *SubscriptionArticleGenerator) Validate() error {
	if s.MuXiCodeDocsPath == "" || s.SubscriptionArticleDir == "" {
		return errors.New("MuXiCodeDocsPath or SubscriptionArticlePath is empty")
	}
	return nil
}
